package com.jmemoir.weixin.mp.service.impl;

import cn.hutool.json.JSONUtil;
import com.jmemoir.weixin.mp.properties.WeiXinMpProperties;
import com.jmemoir.weixin.mp.service.WeiXinMpService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

/**
 * 微信公众号接口
 *
 * @author Tellsea
 * @date 2023/8/15
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WeiXinMpServiceImpl implements WeiXinMpService {

    private final WxMpService wxMpService;
    private final WeiXinMpProperties weiXinMpProperties;

    @Override
    public String getLoginUrl() {
        String authorizationUrl = wxMpService.getOAuth2Service().buildAuthorizationUrl(weiXinMpProperties.getCallbackUrl(), WxConsts.OAuth2Scope.SNSAPI_USERINFO, null);
        return authorizationUrl;
    }

    @Override
    public void callback(HttpServletRequest request, HttpServletResponse response) {
        String code = request.getParameter("code");
        try {
            WxOAuth2AccessToken accessToken = wxMpService.getOAuth2Service().getAccessToken(code);
            // 这里可以拿到：头像、昵称、openId、性别
            WxOAuth2UserInfo userInfo = wxMpService.getOAuth2Service().getUserInfo(accessToken, null);
            log.info("用户信息：{}", JSONUtil.toJsonStr(userInfo));
            // 存入数据库
            // 创建Token
            // 重定向到登录页面，携带Token
            String token = UUID.randomUUID().toString();
            response.sendRedirect(weiXinMpProperties.getLoginSuccessUrl() + "?token=" + token);
        } catch (WxErrorException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
